package top.atcra.rpc.server.shutdown;

import lombok.extern.slf4j.Slf4j;
import top.atcra.rpc.config.ConfigLoader;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.LongAdder;

/**
 * JVM退出时的钩子函数
 *
 * @author atcra
 * @date 2025-3-25
 */
@Slf4j
public class ShutdownHook extends Thread {
    // 是否进入延迟关闭状态
    public static final AtomicBoolean ENTER_DELAY_SHUTDOWN_STATE = new AtomicBoolean(false);

    // 尚未完成的请求
    public static final LongAdder REQUEST_COUNTER = new LongAdder();

    @Override
    public void run() {
        ENTER_DELAY_SHUTDOWN_STATE.set(true);
        log.info("JVM is shutting down, enter delay shutdown state.");

        // 等待未完成的请求全部完成
        long deadline = System.currentTimeMillis() + ConfigLoader.getConfig().getSHUTDOWN_TIMEOUT_MS();

        while (REQUEST_COUNTER.sum() != 0L && System.currentTimeMillis() < deadline) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
